package top.yaofengqiao.springcloudsimple.payment.biz.trigger.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import top.yaofengqiao.springcloudsimple.common.constant.MQConstant;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.entity.PaymentOrderEntity;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.req.PaymentSuccessRequest;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.service.IPaymentService;
import top.yaofengqiao.springcloudsimple.payment.biz.trigger.listener.dto.OrderDeliverDTO;

import javax.annotation.Resource;

/**
 * @author yfq
 * @date 2024/6/19 10:06
 * @description 订单支付成功事务消息监听
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = MQConstant.ORDER_TRANSACTION_TOPIC,
        consumerGroup = MQConstant.ORDER_GROUP,
        selectorExpression = MQConstant.ORDER_PAYMENT_TAG)
public class PaymentSuccessListener implements RocketMQListener<PaymentSuccessRequest> {
    @Resource
    private IPaymentService paymentService;
    @Resource
    private RocketMQTemplate extRocketMQTemplate;

    @Override
    public void onMessage(PaymentSuccessRequest request) {
        log.info("接收到事务消息：{}", JSON.toJSONString(request));
        // 1. 查询充值订单
        PaymentOrderEntity paymentOrderEntity = paymentService.queryByPayOrderNo(request.getOrderNo());

        // 2. 订单发货消息
        OrderDeliverDTO orderDeliverDTO = OrderDeliverDTO.builder()
                .orderNo(paymentOrderEntity.getRechargeOrderNo())
                .payAmount(request.getPayAmount())
                .payTime(request.getPayTime())
                .build();

        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(orderDeliverDTO))
                .setHeader(MQConstant.KEYS, orderDeliverDTO.getOrderNo())
                .build();

        SendResult sendResult = extRocketMQTemplate.syncSend(MQConstant.buildOrderNormalDestination(MQConstant.ORDER_DELIVER_TAG), message);
        log.info("订单发货消息发送结果：{}", JSON.toJSONString(sendResult));

        // 3. TODO 积分增加消息
    }

}
